#include <iostream>
#include <mutex>
#include <thread>

#include <chrono>

using namespace std;
using namespace chrono;

void ThreadDetach() {
    std::thread t1([=]() {
        std::cout << "Hello, Concurrent World 01 !\n";
        });

    std::thread t2([=]() {
        std::cout << "Hello, Concurrent World 02 !\n";
        });

    t1.detach();
    t2.detach();

    std::cout << "the joinable of t1 is: " << t1.joinable() << std::endl;
    std::cout << "the joinable of t2 is: " << t2.joinable() << std::endl;
}

int main() {

    std::thread t1([=]() {
        std::cout << "Hello, Concurrent World 01 !\n";
        });

    std::thread t2([=]() {
        std::cout << "Hello, Concurrent World 02 !\n";
        });

    t1.detach();
    t2.detach();

    std::cout << "the joinable of t1 is: " << t1.joinable() << std::endl;
    std::cout << "the joinable of t2 is: " << t2.joinable() << std::endl;

    std::thread t3([=]() {
        std::cout << "Hello, Concurrent World 03 !\n";
        });

    std::thread t4([=]() {
        std::cout << "Hello, Concurrent World 04 !\n";
        });

    std::cout << "the joinable of t3 is: " << t3.joinable() << std::endl;
    std::cout << "the joinable of t4 is: " << t4.joinable() << std::endl;

    t3.join();
    t4.join();

    std::cout << "the joinable of t3 is: " << t3.joinable() << std::endl;
    std::cout << "the joinable of t4 is: " << t4.joinable() << std::endl;

    // 休眠
    //this_thread::sleep_for(microseconds(100));

    std::thread t5([=]() {
        int cnt = 0;
        while (cnt < 100)
        {
            cout << "Hello, Concurrent World 05 !" << cnt << endl;
            this_thread::sleep_for(microseconds(100));
            cnt++;
        }
    });

    std::thread t6([=]() {
        int cnt = 0;
        while (cnt < 100)
        {
            cout << "Hello, Concurrent World 06 !" << cnt << endl;
            this_thread::sleep_for(microseconds(100));
            cnt++;
        }
    });

    //std::cout << "the joinable of t3 is: " << t3.joinable() << std::endl;
    while (t5.joinable() && t6.joinable())
    {
        this_thread::sleep_for(microseconds(1000));
        cout << "wait for thread 5 and 6\n";
        // t5.join();
        // t6.join();

        t5.detach();
        t6.detach();
    }

    cout << "all thread is over!" << endl;

    return 0;
}
